package com.ekuaitu.kuaitustaff.activity;


import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.ekuaitu.kuaitustaff.R;
import com.ekuaitu.kuaitustaff.api.ApiService;
import com.ekuaitu.kuaitustaff.api.ApiStore;
import com.ekuaitu.kuaitustaff.api.UrlConstant;
import com.ekuaitu.kuaitustaff.application.MyApplication;
import com.ekuaitu.kuaitustaff.base.BaseActivity;
import com.ekuaitu.kuaitustaff.bean.ResultBean;
import com.ekuaitu.kuaitustaff.utils.AppManager;
import com.ekuaitu.kuaitustaff.utils.IntentKey;
import com.ekuaitu.kuaitustaff.utils.IntentUtil;
import com.ekuaitu.kuaitustaff.utils.Logger;
import com.ekuaitu.kuaitustaff.utils.ToastUtils;
import com.ekuaitu.kuaitustaff.utils.ble.BleConstants;
import com.ekuaitu.kuaitustaff.utils.ble.BluetoothHelper;

import java.util.HashMap;

import butterknife.BindView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.ekuaitu.kuaitustaff.utils.ble.BluetoothHelper.REQUEST_OPEN_BLE_ONCE;


public class CarFinishTaskActivity extends BaseActivity {

    @BindView(R.id.tv_intomain)
    TextView tv_intomain;
    @BindView(R.id.tv_closecar)
    TextView tv_closecar;
    private Context mContext = this;
    private String licenseTag, orderId, carId;
    private BleConstants.OperateType operateType;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_car_finishtask;
    }

    @Override
    protected void initView() {
        tv_intomain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BluetoothHelper.getInstance().removeBleInfo(mContext);//finish
                BluetoothHelper.getInstance().stopScanDevice();
                BluetoothHelper.getInstance().disConnectDevice();
                Intent intent = new Intent(mContext, CarNewMainMapActivity.class);
                intent.putExtra("intentFrom",1);
                startActivity(intent);
                AppManager.getAppManager().finishActivity();
            }
        });
        tv_closecar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                operateType = BleConstants.OperateType.CLOSE_DOOR_POWER;
                if (BluetoothHelper.getInstance().isCarSupportBle(mContext)) {
                    showLoadingDialog();
                    //蓝牙开，未连接
                    if (BluetoothHelper.getInstance().isBluetoothOpened() && !BluetoothHelper.getInstance().isConnect()) {
                        BluetoothHelper.getInstance().searchDevice(false, "关门断电", 1, bothSearchResponse);
                    }
                    //蓝牙开，已连接
                    else if (BluetoothHelper.getInstance().isBluetoothOpened() && BluetoothHelper.getInstance().isConnect()) {
                        BluetoothHelper.getInstance().operateCar(true, "关门断电", operateType, onOperateCarListener);
                    }
                    //蓝牙未开
                    else if (!BluetoothHelper.getInstance().isBluetoothOpened()) {
                        BluetoothHelper.getInstance().openBluetooth(CarFinishTaskActivity.this, REQUEST_OPEN_BLE_ONCE);
                    }
                } else {
                    ToastUtils.makeText(mContext, "蓝牙关门失败", ToastUtils.LENGTH_SHORT).show();
                    BluetoothHelper.getInstance().getBleInfo(carId, orderId, licenseTag, mContext, null);
                }
            }
        });
    }


    @Override
    protected void initData() {
        orderId = getIntent().getStringExtra(IntentKey.INTENT_ORDER_ID);
        carId = getIntent().getStringExtra(IntentKey.INTENT_CAR_ID);
        licenseTag = getIntent().getStringExtra(IntentKey.INTENT_LICENSETAG);
    }


    // 锁车 开车的请求接口
    private void controlCar(final String command) {
        showLoadingDialog();
        HashMap<String, String> eventMap = new HashMap<>();
        eventMap.put("action", "重复锁车");
        eventMap.put("comment", "重复锁车");
        eventMap.put("car", licenseTag);
        eventMap.put("order", orderId);
        eventMap.put("command", command);

        new ApiStore().getApiService(UrlConstant.Request.BASE_URL_NEW, "v/car/control", eventMap, new ApiStore.ParseCallBack() {

            @Override
            public void onSaveFailure(String error) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, error, ToastUtils.LENGTH_SHORT).show();
            }


            @Override
            public void onSaveSuccess(ApiService apiService) {
                apiService.controlCar(MyApplication.getInstance().getRequestFieldMap(), orderId, carId, command, "1")
                        .enqueue(new Callback<ResultBean>() {
                            @Override
                            public void onResponse(Call<ResultBean> call, final Response<ResultBean> response) {
                                if (response.isSuccessful() && response.body() != null) {
                                    dismissLoadingDialog();
                                    if (response.body().getErrCode() == 11) {

                                        ToastUtils.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                                        IntentUtil.toLoginActivity(mContext);
                                        AppManager.getAppManager().finishAllActivity();
                                    } else {
                                        ToastUtils.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                                    }
                                } else {
                                    dismissLoadingDialog();
                                    ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                                }
                            }

                            @Override
                            public void onFailure(Call<ResultBean> call, Throwable t) {
                                dismissLoadingDialog();
                                ToastUtils.makeText(mContext, getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
                            }
                        });
            }
        });
    }

    BluetoothHelper.BothSearchResponse bothSearchResponse = new BluetoothHelper.BothSearchResponse() {
        @Override
        public void onSearchSuccess(String mac, String bleName) {
            Logger.i("bleinfo", "onSearchSuccess");
            BluetoothHelper.getInstance().connectDevice(connectResponse, 1);
        }

        @Override
        public void onSearchTimeout() {
            dismissLoadingDialog();
            ToastUtils.makeText(mContext, "未扫描到车", ToastUtils.LENGTH_SHORT).show();
            Logger.i("bleinfo", "扫描超时,任务完成");
            ApiStore.bleRecord("2", orderId, carId, "connect");
        }

        @Override
        public void onSearchTimeoutEveryTime() {

        }
    };

    /**
     * 蓝牙连接的结果
     */
    BluetoothHelper.BothConnectResponse connectResponse = new BluetoothHelper.BothConnectResponse() {
        @Override
        public void onConnectSuccess() {
            Logger.i("bleinfo", "连接上了");
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (operateType == BleConstants.OperateType.CLOSE_DOOR_POWER) {
                        BluetoothHelper.getInstance().operateCar(false, "关门断电", operateType, onOperateCarListener);
                    } else {
                        dismissLoadingDialog();
                    }
                }
            }, 400);
        }

        @Override
        public void onConnectFailed(String error) {
            dismissLoadingDialog();
            ToastUtils.makeText(mContext, "操作失败，请重新尝试" + error, ToastUtils.LENGTH_SHORT).show();
            Logger.i("bleinfo", "连接失败,任务完成");
            ApiStore.bleRecord("2", orderId, carId, "connect");
        }

        @Override
        public void onConnectTimeoutEveryTime() {

        }
    };
    BluetoothHelper.OnOperateCarListener onOperateCarListener = new BluetoothHelper.OnOperateCarListener() {
        @Override
        public void onOperateSuccess(int[] status) {
            dismissLoadingDialog();
            if (operateType == BleConstants.OperateType.CLOSE_DOOR_POWER) {
                ToastUtils.makeText(mContext, "关门成功", ToastUtils.LENGTH_SHORT).show();
            } else {
                ToastUtils.makeText(mContext, "操作成功", ToastUtils.LENGTH_SHORT).show();
            }
            ApiStore.bleRecord("1", orderId, carId, "close");
        }

        @Override
        public void onOperateFailure(String error) {
            dismissLoadingDialog();
            if (operateType == BleConstants.OperateType.CLOSE_DOOR_POWER) {
                ToastUtils.makeText(mContext, "关门失败，请重新尝试", ToastUtils.LENGTH_SHORT).show();
            } else {
                ToastUtils.makeText(mContext, "操作失败", ToastUtils.LENGTH_SHORT).show();
            }
            ApiStore.bleRecord("2", orderId, carId, "close");
        }
    };

    //屏蔽手机返回键
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK)
            return true;//不执行父类点击事件
        return super.onKeyDown(keyCode, event);//继续执行父类其他点击事件
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode != RESULT_OK && requestCode == REQUEST_OPEN_BLE_ONCE) {
            dismissLoadingDialog();
        } else if (resultCode == RESULT_OK && requestCode == REQUEST_OPEN_BLE_ONCE) {
            showLoadingDialog();
            BluetoothHelper.getInstance().searchDevice(false, "关门断电", 1, bothSearchResponse);
        }
    }

}
